<template>
  <div class="ewe-weaning-add-container">
    <!-- 操作按钮区 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button @click="handleCancel">撤销</el-button>
    </div>

    <!-- 表头区域 -->
    <el-card class="header-card" shadow="never">
      <el-form :model="headerForm" label-width="90px" class="header-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="负责人" required>
              <el-select v-model="headerForm.ResponsiblePerson" placeholder="请选择负责人" filterable>
                <el-option v-for="item in userList" :key="item.UserId" :label="item.UserName" :value="item.UserId" />
              </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="断奶日期" required>
              <el-date-picker v-model="headerForm.WeaningDate" type="date" placeholder="请选择断奶日期" style="width: 100%" />
          </el-form-item>
        </el-col>
          <el-col :span="6">
            <el-form-item label="单据号">
              <div style="display: flex; align-items: center; gap: 8px;">
                <el-input v-model="headerForm.DocumentNumber" placeholder="自动生成" readonly />
                <el-button type="primary" size="small" @click="regenerateDocumentNumber">重新生成</el-button>
              </div>
          </el-form-item>
        </el-col>
          <el-col :span="6">
            <el-form-item label="流水号">
              <div style="display: flex; align-items: center; gap: 8px;">
                <el-input v-model="headerForm.SerialNumber" placeholder="自动生成" readonly />
                <el-button type="primary" size="small" @click="regenerateSerialNumber">重新生成</el-button>
              </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    </el-card>

    <!-- 表体区域 -->
    <el-card class="body-card" shadow="never">
      <el-table :data="tableData" border stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="EarTag" label="耳号" width="120" align="center" required>
          <template #default="scope">
            <el-select v-model="scope.row.EarTag" placeholder="请选择耳号" size="small" filterable>
              <el-option v-for="item in earNumberList" :key="item.Id" :label="item.Name" :value="item.Id" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="LactationDays" label="哺乳天数" width="100" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.LactationDays" :min="0" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="CurrentBuilding" label="当前栋舍" width="120" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.CurrentBuilding" placeholder="请选择栋舍" size="small">
              <el-option v-for="item in buildingList" :key="item.BuildingId" :label="item.House_name" :value="item.BuildingId" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="CurrentPen" label="当前栏位" width="120" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.CurrentPen" placeholder="请选择栏位" size="small">
              <el-option v-for="item in penList" :key="item.Id" :label="item.Name" :value="item.Id" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="TransferInBuilding" label="转入栋舍" width="120" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.TransferInBuilding" placeholder="请选择栋舍" size="small">
              <el-option v-for="item in buildingList" :key="item.BuildingId" :label="item.House_name" :value="item.BuildingId" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="TransferInPen" label="转入栏位" width="120" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.TransferInPen" placeholder="请选择栏位" size="small">
              <el-option v-for="item in penList" :key="item.Id" :label="item.Name" :value="item.Id" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="WeaningLambCount" label="断奶只数(只)" width="120" align="center" required>
          <template #default="scope">
            <el-input-number v-model="scope.row.WeaningLambCount" :min="0" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="WeaningTotalWeight" label="断奶总窝重(公斤)" width="140" align="center" required>
          <template #default="scope">
            <el-input-number v-model="scope.row.WeaningTotalWeight" :min="0" :precision="2" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="BreederWeight" label="种母重量(公斤)" width="140" align="center">
          <template #default="scope">
            <el-input-number v-model="scope.row.BreederWeight" :min="0" :precision="2" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="WeaningReason" label="断奶原因" width="150" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.WeaningReason" placeholder="请选择断奶原因" size="small">
              <el-option label="自然断奶" value="自然断奶" />
              <el-option label="强制断奶" value="强制断奶" />
              <el-option label="疾病断奶" value="疾病断奶" />
              <el-option label="其他原因" value="其他原因" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="Status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.Status" placeholder="请选择状态" size="small">
              <el-option label="待审核" value="待审核" />
              <el-option label="已审核" value="已审核" />
              <el-option label="已驳回" value="已驳回" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="80" align="center">
          <template #default="scope">
            <el-button link type="danger" size="small" @click="removeRow(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 表格操作按钮 -->
      <div class="table-actions">
        <el-button type="primary" @click="addRow" icon="Plus">+ 增行</el-button>
        <el-button type="danger" @click="removeLastRow" icon="Minus">- 删行</el-button>
      </div>
    </el-card>

    <!-- 合计区域 -->
    <div class="summary-section">
      <span>合计：</span>
      <span>断奶只数：{{ totalLambCount }}</span>
      <span>断奶总窝重：{{ totalWeight.toFixed(2) }} 公斤</span>
      <span>种母重量：{{ totalBreederWeight.toFixed(2) }} 公斤</span>
    </div>

    <!-- 备注区域 -->
    <el-card class="remark-card" shadow="never">
      <el-form-item label="备注">
        <el-input v-model="headerForm.Remark" type="textarea" placeholder="请输入备注信息" />
      </el-form-item>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { Sheep_BreedingWrite, serviceRead, Sheep_BreedingRead } from '../../utils/Interceptors'
import { createEweWeaning } from '../../utils/EweWeaning'

const router = useRouter()

// 下拉数据
const userList = ref<any[]>([])
const buildingList = ref<any[]>([])
const penList = ref<any[]>([])
const earNumberList = ref<any[]>([]) // 新增耳号列表

// 表头表单数据
const headerForm = reactive({
  ResponsiblePerson: '',
  WeaningDate: '',
  DocumentNumber: '',
  SerialNumber: '',
  Remark: ''
})

// 表体数据
const tableData = ref([
  {
    EarTag: null,
    LactationDays: null,
    CurrentBuilding: '',
    CurrentPen: '',
    TransferInBuilding: '',
    TransferInPen: '',
    WeaningLambCount: null,
    WeaningTotalWeight: null,
    BreederWeight: null,
    WeaningReason: '',
    Status: ''
  }
])

// 计算合计
const totalLambCount = computed(() => 
  tableData.value.reduce((sum, row) => sum + (Number(row.WeaningLambCount) || 0), 0)
)

const totalWeight = computed(() => 
  tableData.value.reduce((sum, row) => sum + (Number(row.WeaningTotalWeight) || 0), 0)
)

const totalBreederWeight = computed(() => 
  tableData.value.reduce((sum, row) => sum + (Number(row.BreederWeight) || 0), 0)
)

// 增加行
const addRow = () => {
  tableData.value.push({
    EarTag: null,
    LactationDays: null,
    CurrentBuilding: '',
  CurrentPen: '',
    TransferInBuilding: '',
  TransferInPen: '',
    WeaningLambCount: null,
    WeaningTotalWeight: null,
    BreederWeight: null,
    WeaningReason: '', // 新增断奶原因
    Status: '待审核' // 新增状态
  })
}

// 删除指定行
const removeRow = (index: number) => {
  if (tableData.value.length > 1) {
    tableData.value.splice(index, 1)
  } else {
    ElMessage.warning('至少保留一行')
  }
}

// 删除最后一行
const removeLastRow = () => {
  if (tableData.value.length > 1) {
    tableData.value.pop()
  } else {
    ElMessage.warning('至少保留一行')
  }
}

// 生成单据号
const generateDocumentNumber = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  
  return `DW${year}${month}${day}${hours}${minutes}${seconds}${random}`
}

// 生成流水号
const generateSerialNumber = () => {
  const now = new Date()
  const timestamp = now.getTime()
  const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
  
  return `LS${timestamp}${random}`
}

// 重新生成单据号
const regenerateDocumentNumber = () => {
  headerForm.DocumentNumber = generateDocumentNumber()
  ElMessage.success('单据号已重新生成')
}

// 重新生成流水号
const regenerateSerialNumber = () => {
  headerForm.SerialNumber = generateSerialNumber()
  ElMessage.success('流水号已重新生成')
}

// 保存
const handleSave = async () => {
  // 验证表头必填项
  if (!headerForm.ResponsiblePerson) {
    ElMessage.error('请选择负责人')
    return
  }
  if (!headerForm.WeaningDate) {
    ElMessage.error('请选择断奶日期')
    return
  }

  // 验证表体数据
  for (let i = 0; i < tableData.value.length; i++) {
    const row = tableData.value[i]
    if (!row.EarTag || row.EarTag === '' || row.EarTag === 0) {
      ElMessage.error(`第${i + 1}行请选择耳号`)
      return
    }
    if (!row.WeaningLambCount || row.WeaningLambCount <= 0) {
      ElMessage.error(`第${i + 1}行断奶只数必须大于0`)
      return
    }
    if (!row.WeaningTotalWeight || row.WeaningTotalWeight <= 0) {
      ElMessage.error(`第${i + 1}行断奶总窝重必须大于0`)
      return
    }
    if (!row.WeaningReason) {
      ElMessage.error(`第${i + 1}行断奶原因不能为空`)
      return
    }
    if (!row.Status) {
      ElMessage.error(`第${i + 1}行状态不能为空`)
      return
    }
  }

  try {
    // 自动生成单据号和流水号
    if (!headerForm.DocumentNumber) {
      headerForm.DocumentNumber = generateDocumentNumber()
    }
    if (!headerForm.SerialNumber) {
      headerForm.SerialNumber = generateSerialNumber()
    }

    // 获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const userName = userInfo.UserName || '系统用户'
    const currentTime = new Date().toISOString()

    // 只处理第一行数据，参考其他页面的提交方式
    const firstRow = tableData.value[0]
    
    // 直接使用与成功记录(ID 8)完全相同的结构
    const payload = {
      dto: {
        EarTag: firstRow.EarTag ? String(firstRow.EarTag) : '',
        WeaningDate: headerForm.WeaningDate ? headerForm.WeaningDate : new Date().toISOString().split('T')[0],
        LactationDays: firstRow.LactationDays ? parseInt(firstRow.LactationDays) : 0,
        BreederWeight: firstRow.BreederWeight ? parseFloat(firstRow.BreederWeight) : 0,
        WeaningLambCount: firstRow.WeaningLambCount ? parseInt(firstRow.WeaningLambCount) : 0,
        WeaningTotalWeight: firstRow.WeaningTotalWeight ? parseFloat(firstRow.WeaningTotalWeight) : 0,
        CurrentPen: firstRow.CurrentBuilding ? String(firstRow.CurrentBuilding) : '',
        CurrentStall: firstRow.CurrentPen ? String(firstRow.CurrentPen) : '',
        TransferInPen: firstRow.TransferInBuilding ? String(firstRow.TransferInBuilding) : '',
        TransferInStall: firstRow.TransferInPen ? String(firstRow.TransferInPen) : '',
        WeaningReason: firstRow.WeaningReason || '',
        Status: firstRow.Status || '待审核',
        DocumentNumber: headerForm.DocumentNumber,
        ResponsiblePerson: String(headerForm.ResponsiblePerson || ''),
        Creator: userName,
        CreateTime: currentTime,
        Modifier: userName,
        ModifyTime: currentTime,
        Approver: userName,
        ApprovalTime: currentTime,
        Remark: headerForm.Remark || ''
      }
    }
    
    console.log('提交数据:', JSON.stringify(payload)) // 打印完整JSON字符串
    console.log('EarTag类型:', typeof payload.dto.EarTag, payload.dto.EarTag)
    
    const res = await Sheep_BreedingWrite.post('/api/EweWeaning/create', payload)
    console.log('API响应:', res)
    if (res.data && res.data.code === 200) {
      ElMessage.success('保存成功')
      router.push('/EweWeaning')
    } else {
      ElMessage.error(res.data?.msg || '保存失败')
      console.error('保存失败详情:', res.data)
    }
  } catch (error: any) {
    console.error('请求异常:', error)
    console.error('请求异常详情:', error.response?.data)
    console.error('请求状态码:', error.response?.status)
    console.error('请求错误信息:', error.message)
    ElMessage.error(error?.response?.data?.msg || error?.message || '保存失败')
  }
}

// 撤销
const handleCancel = () => {
  router.push('/EweWeaning')
}

// 获取用户列表
const fetchUserList = () => {
  serviceRead.get('/api/User/SraechUser').then(res => {
    if (res.data && res.data.code === 200) {
      userList.value = res.data.PageData || []
    } else {
      userList.value = []
    }
  })
}

// 获取栋舍列表
const fetchBuildingList = () => {
  Sheep_BreedingRead.get('/api/Sheepfarm/SearchBuildingManagement', {
    params: { PageIndex: 1, PageSize: 100 }
  }).then(res => {
    console.log('栋舍API返回:', res.data)
    if (res.data && res.data.code === 200) {
      buildingList.value = res.data.PageData || []
      console.log('栋舍列表:', buildingList.value)
    } else {
      buildingList.value = []
      console.log('栋舍API失败:', res.data)
    }
  }).catch(err => {
    console.error('栋舍API错误:', err)
    buildingList.value = []
  })
}

// 获取栏位列表
const fetchPenList = () => {
  Sheep_BreedingRead.get('/api/EliminationInfo/GetFieldManagementIdName').then(res => {
    console.log('栏位API返回:', res.data)
    if (res.data && res.data.code === 200) {
      penList.value = res.data.data || []
      console.log('栏位列表:', penList.value)
    } else {
      penList.value = []
      console.log('栏位API失败:', res.data)
    }
  }).catch(err => {
    console.error('栏位API错误:', err)
    penList.value = []
  })
}

// 获取耳号列表
const fetchEarNumberList = () => {
  Sheep_BreedingRead.get('/api/EliminationInfo/GetSheepFilesIdEarNumber').then(res => {
    console.log('耳号API返回:', res.data)
    if (res.data && res.data.code === 200) {
      earNumberList.value = res.data.data || []
      console.log('耳号列表:', earNumberList.value)
      // 打印第一个耳号的数据结构
      if (earNumberList.value.length > 0) {
        console.log('第一个耳号数据结构:', earNumberList.value[0])
        console.log('第一个耳号的所有字段:', Object.keys(earNumberList.value[0]))
      }
    } else {
      earNumberList.value = []
      console.log('耳号API失败:', res.data)
    }
  }).catch(err => {
    console.error('耳号API错误:', err)
    earNumberList.value = []
  })
}

onMounted(() => {
  fetchUserList()
  fetchBuildingList()
  fetchPenList()
  fetchEarNumberList() // 在页面加载时获取耳号列表
  
  // 页面加载时自动生成单据号和流水号
  headerForm.DocumentNumber = generateDocumentNumber()
  headerForm.SerialNumber = generateSerialNumber()
})
</script>

<style scoped>
.ewe-weaning-add-container {
  min-height: 100vh;
  background: #f7f8fa;
  padding: 24px;
}

.action-bar {
  margin-bottom: 16px;
}

.header-card {
  margin-bottom: 18px;
}

.header-form {
  padding: 12px 0;
}

.body-card {
  margin-bottom: 12px;
}

.table-actions {
  margin-top: 8px;
  display: flex;
  gap: 8px;
}

.summary-section {
  margin: 12px 0 18px 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  display: flex;
  gap: 32px;
}

.remark-card {
  margin-top: 12px;
}
</style> 